package com.wangxinyuchuan.algorithm.phase1;

import java.util.Arrays;

/**
 * @author wangxinyuchuan
 * @version _5_插入排序.java v1.0 2023/5/25 9:53 PM wangxinyuchuan Exp $
 */
public class _5_插入排序 {
    public static void main(String[] args) {
        int[] array = {1, 4, 7, 3, 2, 5, 8, 6};
        System.out.println(Arrays.toString(insertSort(array)));
    }

    /**
     * 插入排序
     * @param array
     * @return
     */
    public static int[] insertSort(int[] array) {
        if (array == null || array.length < 2) {
            return array;
        }
        int length = array.length;
        for (int i = 0; i < length-1; i++) {
            for (int j = i+1; j > 0; j--) {
                if (array[j-1] > array[j]) {
                    swap(array, j, j-1);
                } else {
                    break;
                }
            }
        }
        return array;
    }

    private static void swap(int[] array, int i, int minIndex) {
        int temp = array[i];
        array[i] = array[minIndex];
        array[minIndex] = temp;
    }
}
